<?php
namespace App\Http\Controllers\Game;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Game\GameData;
use App\Models\User\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\UserPlatform;

class GameController extends Controller
{
    public function data(Request $request) {

        if ($request->ajax()) {

            $rows = $request->get("rows");

            $s = "(SELECT MAX(id) AS id2 FROM game_data GROUP BY user_id, \"time\") AS t2";
            
            $GameData = $this->filters($request, new GameData());

//             $admin_id = Auth::user()->user_id;
//             if (!UserPlatform::isAll($admin_id)) {
//                 $GameData = $GameData->join("AWGameUserDB.dbo.UsersInfo", "user_id", "=", "UserID")
//                 ->whereIn("AWGameUserDB.dbo.UsersInfo.SPID", UserPlatform::ids($admin_id));
//             }

            $paginator = $GameData->join(DB::raw($s), "id", "=", "id2")
            ->orderBy("id", "DESC")->paginate($rows);

            $rows = [];
            foreach ($paginator as $page) {

                $rows[] = $page;
            }

            if ($rows) {
                $ids = [];
                foreach ($rows as $p) {
                    $ids[] = $p->user_id;
                }

                $data1 = User::whereIn("UserID", $ids)->get();

                foreach ($rows as $p) {
                    $p->time = date("Y-m-d H:i:s", strtotime($p->time));
                    foreach ($data1 as $p2) {
                        if ($p->user_id == $p2->UserID) {
                            $p->NickName = $p2->NickName;
                        }
                    }
                }
            }

            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            return view("game/data/index");
        }
    }
}
